package com.atguigu.chapter05.transform;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.functions.RichReduceFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

import java.util.ArrayList;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/6/9 13:47
 */
public class Flink09_Reduce {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        
        ArrayList<WaterSensor> waterSensors = new ArrayList<>();
        waterSensors.add(new WaterSensor("sensor_1", 1607527992000L, 20));
        waterSensors.add(new WaterSensor("sensor_1", 1607527994000L, 60));
        waterSensors.add(new WaterSensor("sensor_1", 1607527996000L, 60));
        waterSensors.add(new WaterSensor("sensor_2", 1607527993000L, 10));
        waterSensors.add(new WaterSensor("sensor_2", 1607527995000L, 30));
        // select id,  sum(vc) from t group by id
        env
            .fromCollection(waterSensors)
            .keyBy(WaterSensor::getId)
            .reduce(new RichReduceFunction<WaterSensor>() {
                @Override
                public void open(Configuration parameters) throws Exception {
                    System.out.println("Flink09_Reduce.open");
                }
    
                @Override
                public WaterSensor reduce(WaterSensor v1,
                                          WaterSensor v2) throws Exception {
                    System.out.println("Flink09_Reduce.reduce");
                    // 如果某个key的第一个值处理的时候, 不会执行这个函数
                    return new WaterSensor(v1.getId(), v2.getTs(), v1.getVc() + v2.getVc());
                }
            })
            .print();
        
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
